package com.woniushop.service.imple;

import java.math.BigDecimal;
import java.util.List;

import com.woniushop.dao.GoodsDAO;
import com.woniushop.dao.imple.GoodsDAOImple;
import com.woniushop.entity.Goods;
import com.woniushop.entity.PageBean;
import com.woniushop.service.GoodsService;

/**
 * 商品业务逻辑接口的实现类
 * 
 * @author 崔新雄
 *
 */
public class GoodsServiceImple implements GoodsService {

	private GoodsDAO goodsDAO = new GoodsDAOImple();

	/**
	 * 根据条件分页查询商品数据
	 * 
	 * @param pageBean
	 * @param goods
	 * @return
	 */
	@Override
	public List<Goods> findByPage(PageBean pageBean, Goods goods) {
		// 完善pageBean信息
		Integer totalNum = goodsDAO.count(goods);
		pageBean.setTotalNum(totalNum);

		Integer pageSize = pageBean.getPageSize();
		Integer totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
		totalPage = totalPage == 0 ? 1 : totalPage;
		pageBean.setTotalPage(totalPage);

		// 如果页码超过范围，则设为最后一页
		if (pageBean.getPage() > totalPage) {
			pageBean.setPage(totalPage);
		}

		// 查询用户数据
		List<Goods> list = goodsDAO.findByPage(pageBean.getPage(), pageSize, goods);

		pageBean.setNumsOfCurrPage(list.size());

		return list;
	}

	/**
	 * 增加商品
	 * 
	 * @param goods
	 */
	@Override
	public void add(Goods goods) {
		goodsDAO.add(goods);
	}

	/**
	 * 根据gid查找商品
	 * 
	 * @param gid
	 * @return
	 */
	@Override
	public Goods findOne(Integer gid) {
		return goodsDAO.findOne(gid);
	}

	/**
	 * 更新商品数据
	 * 
	 * @param goods
	 */
	@Override
	public void update(Goods goods) {
		goodsDAO.update(goods);
	}

	/**
	 * 修改商品状态
	 * 
	 * @param gid
	 * @param gstate
	 */
	@Override
	public void changeGstate(Integer gid, Integer gstate) {
		Goods goods = goodsDAO.findOne(gid);
		goods.setGstate(gstate);
		goodsDAO.update(goods);
	}

	/**
	 * 根据商品id返回商品价格
	 * 
	 * @param gid
	 * @return
	 */
	@Override
	public BigDecimal getPriceByGid(Integer gid) {
		Goods goods = goodsDAO.findOne(gid);
		return goods.getGprice();
	}

}
